package com.jic.product.impl;

import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.entity.StoreInventory;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.manage.request.ProductBatchUpdateRequest;
import com.jic.product.manage.request.ShopInfoRequest;
import com.jic.product.manage.response.ShopInfoResponse;
import com.jic.product.mapper.ProductMapper;
import com.jic.product.mapper.StoreInventoryMapper;
import com.jic.product.manage.request.StoreInventoryRequest;
import com.jic.product.manage.response.StoreInventoryResponse;
import com.jic.product.service.StoreInventoryService;
import com.jic.product.util.ExcelImportUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 店铺仓库表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-01-16 04:47:43
 */
@Service
@Slf4j
public class StoreInventoryServiceImpl implements StoreInventoryService {

    @Autowired
    private StoreInventoryMapper storeInventoryMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public long insert(StoreInventory storeInventory) {
        long flag = storeInventoryMapper.insert(storeInventory);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return storeInventoryMapper.delete(id);
    }

    @Override
    public long update(StoreInventory storeInventory) {
        return storeInventoryMapper.update(storeInventory);
    }

    @Override
    public StoreInventory queryByPrimaryKey(Long id) {
        return storeInventoryMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<StoreInventory> query(StoreInventory storeInventory) {
        return storeInventoryMapper.query(storeInventory);
    }

    @Override
    public PageResult<StoreInventoryResponse> queryPage(StoreInventoryRequest storeInventory, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<StoreInventoryResponse> list = storeInventoryMapper.queryPage(startIndex, pageQuery.getLimit(), storeInventory);
        long count = storeInventoryMapper.queryPageCount(storeInventory);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult batchUpdateProductStock(ProductBatchUpdateRequest productBatchUpdateRequest) {
        log.info("开始进入批量修改商品库存------------》" + productBatchUpdateRequest.toString());
        try {
            if (productBatchUpdateRequest != null && CollectionUtils.isNotEmpty(productBatchUpdateRequest.getProductBatchUpdateRequestList())) {
                productBatchUpdateRequest.getProductBatchUpdateRequestList().forEach(item -> {
                    StoreInventory storeInventory = storeInventoryMapper.queryByProductId(item.getId());
                    if (storeInventory != null) {
                        ProductBatchUpdateRequest pro = new ProductBatchUpdateRequest();
                        Long availableStock = item.getNum() - storeInventory.getBlockStock();
                        if (availableStock > 0) {
                            pro.setNum(item.getNum());
                            pro.setId(item.getId());
                            storeInventoryMapper.batchUpdateProductStock(pro);
                        }
                    }
                });
            } else {
                return RestResult.error("9999", "参数异常");
            }
        } catch (Exception e) {
            log.error("修改商品价格异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
        return RestResult.success(true);
    }


    /**
     * 通过导入店铺商品修改商品库存
     *
     * @param fileName
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult byExcelUpdateProductStock(String fileName, MultipartFile file) throws Exception {
        //验证EXCEL文件
        if (!ExcelImportUtils.validateExcel(fileName)) {
            return RestResult.error("9999", "上传文件格式不正确");
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        Map<String, PictureData> mapList = null;
        //店铺商品
        Sheet sheet = null;
        //2003的excel
        if (ExcelImportUtils.isExcel2003(fileName)) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        sheet = wb.getSheetAt(0);
        if (sheet == null) {
            return RestResult.error("9999", "数据不存在");
        }
        //r = 2 表示从第三行开始循环 如果你的第三行开始是数据
        List<ProductBatchUpdateRequest> productBatchUpdateRequestList = new ArrayList<>();
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            //通过sheet表单对象得到 行对象
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //导入数据请求
            ProductBatchUpdateRequest productBatchUpdateRequest = new ProductBatchUpdateRequest();
            //共4列表数据
            for (int j = 0; j < 4; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (j == 0) {
                        productBatchUpdateRequest.setId(Long.valueOf(cell.getStringCellValue()));
                    } else if (j == 3) {
                        productBatchUpdateRequest.setNum(Long.valueOf(cell.getStringCellValue()));
                    }
                }
            }
            productBatchUpdateRequestList.add(productBatchUpdateRequest);

        }
        ProductBatchUpdateRequest productBatchUpdateRequest1 = new ProductBatchUpdateRequest();
        productBatchUpdateRequest1.setProductBatchUpdateRequestList(productBatchUpdateRequestList);
        if (CollectionUtils.isNotEmpty(productBatchUpdateRequest1.getProductBatchUpdateRequestList())) {
            this.batchUpdateProductStock(productBatchUpdateRequest1);
        }
        return RestResult.success(true);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult batchUpdateAvailableStock() {
        log.info("开始进入批量修改商品每日库存------------》");
        try {
            //查询店铺不入仓商品
            ShopInfoRequest shopInfoRequest = new ShopInfoRequest();
            shopInfoRequest.setWarehousingFlag(0);
            List<ShopInfoResponse> shopInfoResponseList = productMapper.queryShopProductList(shopInfoRequest);
            if (CollectionUtils.isNotEmpty(shopInfoResponseList)) {
                shopInfoResponseList.forEach(item -> {
                    if (null == item.getStockId() || null==item.getDayStock()) {

                    } else {
                        StoreInventory storeInventory=new StoreInventory();
                        storeInventory.setId(item.getStockId());
                        storeInventory.setAvailableStock(item.getDayStock());
                        storeInventoryMapper.update(storeInventory);
                    }
                });
            }

        } catch (Exception e) {
            log.error("修改商品每日库存", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
        return RestResult.success(true);
    }


    @Override
    public Integer queryByProductIds(List<Long> productIds) {
        return storeInventoryMapper.queryByProductIds(productIds);
    }
}
